//
//  LoadMoreScrollView.swift
//  FoodStore
//
//  Created by youwei on 2025/5/8.
//

import SwiftUI

struct RefreshableLoadMoreScrollView<Content: View>: View {
    let threshold: CGFloat
    let isLoadingMore: Bool
    let hasMore: Bool
    let itemSpace: CGFloat
    let onRefresh: () async -> Void
    let onLoadMore: () -> Void
    let content: () -> Content

    init(threshold: CGFloat = 100,
         isLoadingMore: Bool,
         hasMore: Bool,
         itemSpace: CGFloat = 8.0,
         @ViewBuilder content: @escaping () -> Content,
         onRefresh: @escaping () async -> Void,
         onLoadMore: @escaping () -> Void) {
        self.threshold = threshold
        self.isLoadingMore = isLoadingMore
        self.hasMore = hasMore
        self.itemSpace = itemSpace
        self.content = content
        self.onRefresh = onRefresh
        self.onLoadMore = onLoadMore
    }

    var body: some View {
        ScrollView(showsIndicators: false, content: {
            LazyVStack(spacing: itemSpace) {
                content()
                GeometryReader { geometry in
                    Color.clear
                        .onAppear {
                            let y = geometry.frame(in: .global).minY
                            let screenHeight = UIScreen.main.bounds.height
                            if y < screenHeight + threshold && hasMore && !isLoadingMore {
                                Log.debug("加载更多。。。")
                                onLoadMore()
                            }
                        }
                        .frame(height: 40)
                }

                if isLoadingMore {
                    ProgressView("加载中...")
                        .foregroundStyle(Color.fs000000)
                        .padding()
                } else if !hasMore {
                    Text("没有更多数据了")
                        .foregroundColor(.gray)
                        .padding()
                }
            }
        })
        .refreshable {
            await onRefresh()
        }
    }
}
